import Vue from 'vue'
import Utils from '@/common/utils.js'
import Router from 'vue-router'
import tabletRoutes from '@/router/tablet_router'
import mobileRoutes from '@/router/mobile_router'

Vue.use(Router)
let routes
if (navigator.isPc) {
  window.location.href = 'http://www.baidu.com/'
} else if (navigator.isTablet) {
  routes = tabletRoutes
} else {
  routes = mobileRoutes
}

const router = new Router({
  mode: 'history',
  base: __dirname,
  routes
})

// 判断是手机还是pc
function navigator () {
  let ua = navigator.userAgent
  let isWindowsPhone = /(?:Windows Phone)/.test(ua)
  let isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone
  let isAndroid = /(?:Android)/.test(ua)
  let isFireFox = /(?:Firefox)/.test(ua)
  let isTablet = /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox && /(?:Tablet)/.test(ua))
  let isPhone = /(?:iPhone)/.test(ua) && !isTablet
  let isChrome = /(?:Chrome|CriOS)/.test(ua)
  let isPc = !isPhone && !isAndroid && !isSymbian

  return {
    isTablet: isTablet,
    isPhone: isPhone,
    isAndroid: isAndroid,
    isPc: isPc,
    isChrome: isChrome,
    isFireFox: isFireFox,
    navigator: ua
  }
}

// 路由跳转之前操作
router.beforeEach((to, from, next) => {
  // 修改页面title
  if (to.meta && to.meta.title) {
    document.title = to.meta.title
  }
  // next()
  let userData = Utils.local('userData')
  if (to.meta.checkLogin) {
    if (to.query && to.query.lg) {
      next()
    } else if (userData) {
      next()
    } else {
      next({ path: '/login' })
    }
  } else {
    next()
  }
})

// 跳转页面回到顶部
router.afterEach((to, from, next) => {
  window.scrollTo(0, 0)
})

export default router
